package com.uusee.crawler.pageprocessor.video.youku;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.uusee.crawler.framework.Processor;
import com.uusee.crawler.model.CrawlStatusCodes;
import com.uusee.crawler.model.CrawlURI;
import com.uusee.crawler.util.DomainUtils;
import com.uusee.crawler.util.PageProcessorUtils;
import com.uusee.shipshape.sp.model.Ugc;
import com.uusee.util.StringUtils;

public class YoukuGetPlayListInterfacePageProcessor extends Processor {
	private static Log log = LogFactory.getLog("YoukuGetPlayListInterfacePageProcessor"); 
	Map<String,String> channelMap = new HashMap<String,String>();
	Map<String,String> categoryMap = new HashMap<String,String>();
	
	public void setChannelMap(Map<String, String> channelMap) {
		this.channelMap = channelMap;
	}

	public void setCategoryMap(Map<String, String> categoryMap) {
		this.categoryMap = categoryMap;
	}

	private boolean canProcess(CrawlURI crawlURI) {
		int crawlStatus = crawlURI.getCrawlStatus();
		if (crawlStatus == CrawlStatusCodes.FETCH_SUCCESS) {
			return true;
		} else if (crawlStatus == CrawlStatusCodes.FETCH_SC_NOT_OK) {
			crawlURI.setCrawlStatus(CrawlStatusCodes.PAGE_PROCESS_INVALID);
			return false;
		} else {
			return false;
		}
	}

	public void innerProcess(CrawlURI crawlURI) {
		if (!canProcess(crawlURI)) {
			return;
		}
		Date crawlDate = new Date();
		String crawlUser = "uusee_crawler";
		String videoSite = crawlURI.getSourceSite();
		String crawlUrl = crawlURI.getCrawlUrl();
		String crawlResult = crawlURI.getCrawlResult();
		
		Ugc ugc = (Ugc)crawlURI.getModel();
		if (ugc==null) {
			ugc = new Ugc();
		}
		String id = ugc.getVid();
		
		String vid = id;
		String evid = "X"+YoukuVideoUtils.encodeVid(vid);
		String playUrl = "http://v.youku.com/v_show/id_"+evid+".html";
		String shareUrl = "http://player.youku.com/player.php/sid/"+evid+"/v.swf";
		String playSite = PageProcessorUtils.getValue("http://([^/]*?)/", playUrl);
		String domain = DomainUtils.getDomain(playUrl);
		
		ugc.setVideoSite(videoSite);
		ugc.setDomain(domain);
		ugc.setSourceSite(playSite);
		ugc.setPlayUrl(playUrl);
		ugc.setVid(vid);
		ugc.setEvid(evid);
		try {
			if (StringUtils.isEmpty(crawlResult)) {
				ugc.setStatus("0");
				log.info(videoSite+"-"+id+"-数据不存在。");
				crawlURI.setCrawlStatus(CrawlStatusCodes.PAGE_PROCESS_INVALID);
				return;
			}
			
			JSONObject jsonObject = JSONObject.fromObject( crawlResult ); 
			JSONArray dataJSONArray = jsonObject.getJSONArray("data");
			if (dataJSONArray.size()==0) {
				ugc.setStatus("0");
				log.info(videoSite+"-"+id+"-数据不存在。");
				crawlURI.setCrawlStatus(CrawlStatusCodes.PAGE_PROCESS_INVALID);
				return;
			}
			
			JSONObject videoJsonObject = dataJSONArray.getJSONObject(0);
			
			if (videoJsonObject.containsKey("error")) {
				String error = videoJsonObject.getString("error");
				log.info(videoSite+"-"+id+"-数据已经失效,原因："+error);
				ugc.setStatus("0");
				crawlURI.setCrawlStatus(CrawlStatusCodes.PAGE_PROCESS_INVALID);
				return;
			}
			
			vid = videoJsonObject.getString("videoid");
			evid = "X"+YoukuVideoUtils.encodeVid(vid);
			playUrl = "http://v.youku.com/v_show/id_"+evid+".html";
			shareUrl = "http://player.youku.com/player.php/sid/"+evid+"/v.swf";
			playSite = PageProcessorUtils.getValue("http://([^/]*?)/", playUrl);
			domain = DomainUtils.getDomain(playUrl);
			String title = videoJsonObject.getString("title");
			String logo = videoJsonObject.getString("logo");
			String channelId = videoJsonObject.getString("categories");
			String channel = "";
			if (channelMap.containsKey(channelId)) {
				channel = channelMap.get(channelId);
			}
			String categories = videoJsonObject.getString("cs");
			String[] categoryIdArray = categories.split("\\|");
			StringBuffer categorysSb = new StringBuffer();
			String categorys = "";
			for (String categoryId:categoryIdArray) {
				if (categoryMap.containsKey(categoryId)) {
					String category = categoryMap.get(categoryId);
					categorysSb.append(category);
					categorysSb.append(",");
				}
			}
			if (categorysSb.length()>0) {
				categorys = categorysSb.substring(0, categorysSb.length()-1);
			}
			
			JSONArray tagsJSONArray = videoJsonObject.getJSONArray("tags");
			Iterator tagsIt = tagsJSONArray.iterator();
			StringBuffer tagSb = new StringBuffer();
			String tags = "";
			while(tagsIt.hasNext()) {
				String tag = (String)tagsIt.next();
				tagSb.append(tag);
				tagSb.append(",");
			}
			if (tagSb.length()>0) {
				tags = tagSb.substring(0, tagSb.length()-1);
			}
			int length = videoJsonObject.getInt("seconds");
			String quality = videoJsonObject.getString("ct");
			
			JSONArray streamtypesJSONArray = videoJsonObject.getJSONArray("streamtypes");
			Iterator streamtypesIt = streamtypesJSONArray.iterator();
			StringBuffer fileExtSb = new StringBuffer();
			String fileExt = "";
			List<String> fileExtList = new ArrayList<String>();
			while(streamtypesIt.hasNext()) {
				String fe = (String)streamtypesIt.next();
				fileExtSb.append(fe);
				fileExtSb.append(",");
				fileExtList.add(fe);
			}
			if (fileExtSb.length()>0) {
				fileExt = fileExtSb.substring(0, fileExtSb.length()-1);
			}
			
			JSONObject streamsizesJSONObject = videoJsonObject.getJSONObject("streamsizes");
			long fileSize = 0l;//字节
			for (String fe:fileExtList) {
				fileSize = streamsizesJSONObject.getLong(fe);
			}
			
			
			String uploadUserid = videoJsonObject.getString("userid");
			String eUploadUserid = "U"+YoukuVideoUtils.encodeVid(uploadUserid);
			String uploadUsername = videoJsonObject.getString("username");
			String uploadUserblog = "http://u.youku.com/user_show/id_"+eUploadUserid+".html";
			
			if (length<=1 || fileSize<=0 || StringUtils.isEmpty(logo) || StringUtils.isEmpty(title)) {
				log.info(videoSite+"-"+id+"-数据已经失效。");
				crawlURI.setCrawlStatus(CrawlStatusCodes.PAGE_PROCESS_INVALID);
				return;
			}
			
			ugc.setVideoSite(videoSite);
			ugc.setDomain(domain);
			ugc.setSourceSite(playSite);
			ugc.setPlayUrl(playUrl);
			ugc.setTitle(title);
			ugc.setLogo(logo);
			ugc.setLength(length);
			//ugc.setQuality(quality);
			ugc.setChannel(channel);
			ugc.setCategory(categorys);
			ugc.setTags(tags);
			//ugc.setSummary(summary);
			ugc.setVid(vid);
			ugc.setEvid(evid);
			ugc.setOriLogo(logo);
			ugc.setShareUrl(shareUrl);
			//ugc.setTotalPageView(pv);
			//ugc.setTotalComment(0);
			//ugc.setTotalFav(0);
			ugc.setFileExt(fileExt);
			ugc.setFileSize(fileSize);
			ugc.setUploadUserid(uploadUserid);
			ugc.setUploadUsername(uploadUsername);	
			ugc.setUploadUserblog(uploadUserblog);
			//ugc.setUploadDate();
			ugc.setLogoStatus("0");
			ugc.setStatus("1");
			ugc.setCrawlUser(crawlUser);
			ugc.setCrawlDate(crawlDate);
			ugc.setUpdateUser(crawlUser);
			ugc.setUpdateDate(crawlDate);
			crawlURI.setCrawlStatus(CrawlStatusCodes.PAGE_PROCESS_SUCCESS);
		} catch (Exception e) {
			e.printStackTrace();
			log.error(videoSite+"-"+id+"-处理时发生错误。",e);
			crawlURI.setCrawlStatus(CrawlStatusCodes.PAGE_PROCESS_EXCEPTION);
		}
		
	}

}
